/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
function TreeNode(val, left, right) {
    this.val = (val === undefined ? 0 : val)
    this.left = (left === undefined ? null : left)
    this.right = (right === undefined ? null : right)
}
let a, b, c, d, e, f, g;



d = new TreeNode(5, null, null)
e = new TreeNode(6, null, null)
f = new TreeNode(7, null, null)
g = new TreeNode(8, null, null)


c = new TreeNode(4, g, null)
b = new TreeNode(3, e, f)
a = new TreeNode(2, c, d)
let root = new TreeNode(1, a, b)
// 迭代中序写法
var inorderTraversal = function (outroot) {
    function sort(root) {
        if (!root) return [];
        let stack = [root];
        let res = [];
        let cur = root;
        while (cur) {
            cur = cur.left
            cur && stack.push(cur)
        }
        let list = stack.map((item)=>item.val)
        console.log(list);
        for (let index = stack.length-1; index >= 0; index--) {
            res.push(stack[index].val);
            stack[index].right && (res = res.concat(sort(stack[index].right)));
        }
        return res

    }
   
    return sort(outroot)
};

inorderTraversal(root)


var inorderTraversal2 = function (root, res = []) {
    const stack = [];
    let cur = root;
    while (stack.length || cur) {
        if (cur) {
            stack.push(cur);
            // 左
            cur = cur.left;
        } else {
            // --> 弹出 中
            cur = stack.pop();
            res.push(cur.val);
            // 右
            cur = cur.right;
        }
    };
    console.log('正确验证', res);
    return res;
};

inorderTraversal2(root)